﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Windows.Threading;
using System.Threading;

namespace MiniChat
{
    /// <summary>
    /// Interaction logic for Chat.xaml
    /// </summary>
    public partial class Chat : Window
    {
        public Socket connectedsock;
        private int buffersize = 1024;
        public bool islogged = true;
        DispatcherTimer dstm = new DispatcherTimer(){
            Interval = new TimeSpan(0,0,1)
        };
      

        public Chat()
        {
            InitializeComponent();
            dstm.Tick += new EventHandler(dstm_Tick);
            dstm.Start();
            Thread sth = new Thread(
                new ThreadStart(ListenData));
            sth.SetApartmentState(ApartmentState.MTA);
            sth.Start();
            CGlobalVariable.imgUserAvatar = imgMyAvatar;
            CGlobalVariable.txtStatustext = txtStatusText;
            CGlobalVariable.lsbContacts = lsbContacts;
            CGlobalVariable.txtName = txtName;
        }

        void dstm_Tick(object sender, EventArgs e)
        {
            if (CGlobalVariable.IsDisconnected) {
                CGlobalVariable.IsDisconnected = false;
                this.Close();
            }
        }

      

        private void grCaption_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }
        void ListenData()
        {
            Byte[] contextbytes = null;
            do
            {
                Byte[] bytes = new byte[buffersize];
                try
                {
                    int i = connectedsock.Receive(bytes);
                    Array.Resize<Byte>(ref bytes, i);
                    if (i < buffersize)
                    {
                        String datatext = "";
                        if (contextbytes == null)
                        {
                            datatext = (Encoding.UTF8.GetString(bytes));
                            bytes = null;
                        }
                        else
                        {
                            datatext = (Encoding.UTF8.GetString(contextbytes));
                            contextbytes = null;
                        }
                        Console.WriteLine(datatext);
                        var listcommand = Ullity.Split(datatext, "\n");
                        foreach (string strdata in listcommand)
                        {

                            Client.ProcessMessage(strdata, connectedsock,ref islogged);
                          
                        }
                    }
                    else
                    {
                        if (contextbytes == null)
                        {
                            contextbytes = new byte[buffersize - 1];
                            bytes.CopyTo(contextbytes, 0);
                            bytes = null;
                        }
                        else
                        {
                            Array.Resize(ref contextbytes, contextbytes.Length + i);
                            bytes.CopyTo(contextbytes, contextbytes.Length - i);
                            bytes = null;
                        }

                    }
                    if (i == 0) { System.Threading.Thread.Sleep(100); }

                }
                catch (Exception ex)
               {
                  Console.WriteLine(ex.Message);
                  return;// close sock
               }

            } while (true);
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Client.Send("quit:", connectedsock);
            connectedsock.Close();
            MainWindow frmMain = new MainWindow();
            frmMain.txtUserName.Text = CGlobalVariable.UserName;
            frmMain.Show();
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (Ullity.Trim(txtSearch.Text) != "") {
                Client.Send("adduser:" + Ullity.EncodeString(txtSearch.Text),connectedsock);
            }
        }

        private void lsbContacts_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {            
            ContactItem ci =(ContactItem)((StackPanel)(lsbContacts.SelectedItem)).Tag;
            foreach (Object o in lsbCurrentChat.Items) {
                ContactItem co = (ContactItem)((StackPanel)(o)).Tag;
                if (co.ContactName == ci.ContactName) {
                    lsbCurrentChat.SelectedItem = o;
                    return;
                }
            }
            Image img = (Image)((StackPanel)(lsbContacts.SelectedItem)).Children[0];
            SolidColorBrush sbr = new SolidColorBrush(Color.FromArgb(100, 100, 100, 100));
            if (ci.ContastStatus == 1)
            {
                sbr = new SolidColorBrush(Color.FromArgb(80, 142, 255, 1));
            }

            StackPanel lbst = new StackPanel()
            {
                Height = 48,
                Width = 48,
                Background = sbr,
                Margin = new Thickness(2),
                Tag = ci,
            };
          
            Image i = new Image()
            {
                Height = 24,
                Width = 24,
                VerticalAlignment = System.Windows.VerticalAlignment.Center,
                Source = img.Source
            };
            TextBlock tbfname = new TextBlock()
            {
                Text = ci.ContactFullName,
                FontSize = 8,
                TextAlignment = TextAlignment.Center
            };            
            lbst.Children.Add(i);
            lbst.Children.Add(tbfname);
            lsbCurrentChat.Items.Add(lbst);
            lsbCurrentChat.SelectedItem = lbst;

        }

        private void btnPin_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            if (!CGlobalVariable.IsPin)
            {
                cldfContacts.Width = new GridLength(0);
                cldfChats.Width = new GridLength(1, GridUnitType.Star);
                BitmapImage bi = new BitmapImage(new Uri("/Images/Shortcuts.png", UriKind.Relative));
                btnPin.Source = bi;
            }
            else {
                cldfContacts.Width = new GridLength(1,GridUnitType.Star);
                cldfChats.Width = new GridLength(250);
                BitmapImage bi = new BitmapImage(new Uri("/Images/Pin.png", UriKind.Relative));
                btnPin.Source = bi;
            }
            CGlobalVariable.IsPin = !CGlobalVariable.IsPin;
        }

        private void lsbContacts_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lsbContacts.SelectedItem != null)
            {
                cldfRecylebin.Width = new GridLength(40, GridUnitType.Pixel);
            }
            else {
                cldfRecylebin.Width = new GridLength(0, GridUnitType.Pixel);
            }
        }

        private void imgDelete_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ContactItem ct = (ContactItem)((StackPanel)lsbContacts.SelectedItem).Tag;
            Client.Send("deletefriend:" + ct.ContactName, connectedsock);
        }

        private void lsbCurrentChat_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lsbCurrentChat.SelectedItem != null)
            {
                txtChat.IsEnabled = true;
            }
            else {
                txtChat.IsEnabled = false;
            }
        }



       



        
    }
}
